import axios from "axios"
import { useSelector } from "react-redux"  //引入store工具
import router from "../router"  //引入router
import { message } from "antd"

const service = axios.create({
  baseURL: "/bill",
  timeout: 10000
})

// 添加请求拦截器
service.interceptors.request.use(config => {
  let token = localStorage.getItem('token')
//   console.log('--------请求拦截器token',token)
  config.headers.token = token
  config.headers.Authorization = token
  if(localStorage.getItem("cloudjsToken")){
    let cloudjsToken = localStorage.getItem("cloudjsToken")
    let tokenWithoutBearer = cloudjsToken.replace('Bearer ', '');
    config.headers.token = tokenWithoutBearer
    config.headers.Authorization = tokenWithoutBearer
  }
  return config
})

// 响应拦截器
service.interceptors.response.use()

// 响应拦截器重写 ---- 等可以判断错误了打开这里和上面引入router和message的注释 --- 删除上面一排拦截器
service.interceptors.response.use(response => {
    const { code, msg, data } = response.data //解构出正确和错误，注意变量
  if (code===200||code===0) {
    return data
  } else {
    message.error(msg)
    return Promise.reject(new Error(msg))
  }
},
error => {
    //如果token失效401
  if (error.response?.status === 401) {
    message.error("token失效")
    localStorage.removeItem("token")
    router.navigate("/login")
  }
  return Promise.reject(error)
})


export default service
